﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Maverick.Domain.Abstract;
using Maverick.Domain.Entities;
using Maverick.WebUI.Models;

namespace Maverick.WebUI.Controllers
{
    public class MessagesController : Controller
    {
        private IMessagesRepository messagesRepository;

        public MessagesController(IMessagesRepository messagesRepository)
        {
            this.messagesRepository = messagesRepository;
        }

        public ActionResult List(int parentID)
        {
            var messages = messagesRepository.Messages.Where(x => x.ParentID == parentID);
            var parent = messagesRepository.Messages.Where(x => x.MessageID == parentID).SingleOrDefault();
            
            messages.OrderBy(x => x.DateTime);            

            var model = new MessageListViewModel {Parent = parent, Messages = messages.ToList()};
            
            return View(model);
        }

        public ActionResult Edit(int messageID, int parentID)
        {
            var message = messagesRepository.Messages.First(x => x.MessageID == messageID);
            return View(message);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Message message)
        {
            if (ModelState.IsValid)
            {
                messagesRepository.SaveMessage(message);

                Message parent = messagesRepository.Messages.Where(x => x.MessageID == message.ParentID).SingleOrDefault();

                return RedirectToAction("List", new RouteValueDictionary( new { parentID = message.ParentID, title = parent.TitleUrl }));
            }

            return View(message);
        }

        public ActionResult Delete(int messageID)
        {
            Message message = messagesRepository.Messages.Where(x => x.MessageID == messageID).SingleOrDefault();
            messagesRepository.DeleteMessage(message);

            Message parent = messagesRepository.Messages.Where(x => x.MessageID == message.ParentID).SingleOrDefault();

            return RedirectToAction("List", new RouteValueDictionary(new {parentID = message.ParentID, title = parent.TitleUrl}));
        }

        public ActionResult Add(int parentID)
        {
            Message message = new Message {ParentID = parentID, DateTime = DateTime.Now, CategoryID = null};

            return View("Edit", message);
        }
    }
}
